﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dos.ORM;
using Model;

namespace JFLogic.Logic.CodeRepo
{
    public class CodeRepoLogic
    {
        public int Save(TB_Code_Repo cpInfo)
        {
            return DB.Context.Insert<TB_Code_Repo>(cpInfo);
        }

        /// <summary>
        /// 根据sid获取已识别资源
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public TB_Code_Repo GetBySessionId(string sid)
        {
            return DB.Context.From<TB_Code_Repo>()
                .Where(d => (d.SessionId == sid)).First();
        }

        /// <summary>
        /// 根据sid更新资源信息
        /// </summary>
        /// <param name="cpInfo"></param>
        /// <returns></returns>
        public int Update(TB_Code_Repo cpInfo)
        {
            return DB.Context.Update<TB_Code_Repo>(cpInfo, d => d.SessionId == cpInfo.SessionId);
        }

        /// <summary>
        /// 获取验证码仓库中可用的资源，并标记为占用
        /// </summary>
        /// <param name="timeOut">超时时间，单位为分钟</param>
        /// <returns></returns>
        public TB_Code_Repo GetModelByNewId(int timeOut)
        {
            TB_Code_Repo codeRepo = DB.Context.From<TB_Code_Repo>()
                .Where(d => (d.CodeState == CodeState.RECOGNIZE && d.STime >= DateTime.Now.AddMinutes(0 - timeOut)))
                .OrderBy(d => new { d.STime })
                .First();
            if (codeRepo != null)
            {
                codeRepo.CodeState = CodeState.EMPLOY;
                Update(codeRepo);
            }
            return codeRepo;

        }

        /// <summary>
        /// 获取尚未使用的验证码个数
        /// </summary>
        /// <param name="timeOut">超时时间，单位为分钟</param>
        /// <returns></returns>
        public int getUnUsedRepoCount(int timeOut)
        {
            return DB.Context.Count<TB_Code_Repo>
                (d => (d.CodeState == CodeState.RECOGNIZE
                    && d.STime >= DateTime.Now.AddMinutes(0 - timeOut)));

        }

        /// <summary>
        /// 获取识别失败的验证码
        /// </summary>
        /// <returns></returns>
        public TB_Code_Repo GetFailRepo()
        {
            return DB.Context.From<TB_Code_Repo>()
                .Where(d => d.CodeState == CodeState.FAILED && d.ReportState == null && d.CodeId != null)
                .ToFirst();
        }
    }
}
